<template>
  <div class="add-in-storage">
    <el-card>
      <div class="form-title">编辑报损单</div>
      <el-form :model="form" :rules="rules" ref="formRef" label-width="120px">
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="报损单号">
              <el-input
                v-model="form.reporting_LossesCode"
                placeholder="可不填写，自动生成"
                :readonly="true"
                disabled
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="报损类型" prop="losses_Type">
              <el-select
                v-model="form.losses_Type"
                placeholder="请选择报损类型"
              >
                <el-option label="损坏报损" value="损坏报损" />
                <el-option label="丢失报损" value="丢失报损" />
                <el-option label="其他报损" value="其他报损" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="关联订单号">
              <el-input v-model="form.orderCode" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="制单人">
              <el-input v-model="form.creatorName" :readonly="true" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="制单时间">
              <el-date-picker
                v-model="form.createTime"
                type="date"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="备注">
              <el-input
                v-model="form.notes"
                type="textarea"
                :rows="2"
                maxlength="300"
                show-word-limit
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-card>

    <el-card style="margin-top: 20px">
      <template #header>
        <div
          style="
            display: flex;
            justify-content: space-between;
            align-items: center;
          "
        >
          <span class="form-title">报损产品信息</span>
          <el-button type="primary" @click="fetchProductOptions"
            >新增产品</el-button
          >
        </div>
      </template>
      <el-table :data="productList" border>
        <el-table-column type="selection" width="50" />
        <el-table-column prop="product_Name" label="产品名称" />
        <el-table-column prop="product_Number" label="产品编码" />
        <el-table-column prop="specifications" label="规格" />
        <el-table-column prop="batch" label="批次" />
        <el-table-column prop="price" label="单价" />
        <el-table-column prop="lossesCount" label="报损数">
          <template #default="scope">
            <el-input
              v-model="scope.row.lossesCount"
              placeholder="输入报损数量"
            />
          </template>
        </el-table-column>
        <el-table-column prop="original_location" label="当前库位">
          <template #default="scope">
            <el-input
              v-model="scope.row.original_location"
              placeholder="输入当前库位"
            />
          </template>
        </el-table-column>
        <el-table-column label="操作" width="80">
          <template #default="scope">
            <el-button
              type="text"
              @click="removeProduct(scope.$index, scope.row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <div style="text-align: center; margin-top: 30px">
      <el-button type="primary" @click="onSubmit">提交</el-button>
      <el-button @click="onCancel">取消</el-button>
    </div>

    <!-- 选择产品弹窗 -->
    <el-dialog v-model="showProductDialog" title="选择产品" width="80%">
      <!-- 查询区域 -->
      <div style="margin-bottom: 10px; display: flex; align-items: center">
        <el-input
          v-model="searchForm.product_Number"
          placeholder="请输入编码"
          style="width: 180px; margin-right: 10px"
        />
        <el-input
          v-model="searchForm.product_Name"
          placeholder="请输入名称"
          style="width: 180px; margin-right: 10px"
        />
        <el-button type="primary" @click="fetchProductOptions">搜索</el-button>
      </div>
      <!-- 商品表格 -->
      <el-table
        :data="productOptions"
        border
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="50" />
        <el-table-column prop="product_Number" label="产品编码" />
        <el-table-column prop="product_Name" label="产品名称" />
        <el-table-column prop="specifications" label="规格" />
        <el-table-column prop="category_Name" label="类别" />
        <el-table-column prop="storage_Unit" label="存储单位" />
        <el-table-column prop="packaging_Type" label="包装类型" />
        <el-table-column prop="price" label="单价" />
        <el-table-column prop="weight" label="重量" />
      </el-table>
      <table>
        <tr>
          <td>
            <el-pagination
              v-model:current-page="pageQuery1.pageindex"
              v-model:page-size="pageQuery1.pagesize"
              :page-sizes="[15, 20, 30]"
              :size="size"
              background="true"
              layout="slot, sizes"
              :total="pageQuery1.totalCount"
            >
              共{{ pageQuery1.totalCount }}条 每页显示{{
                pageQuery1.pagesize
              }}条 当前第{{ pageQuery1.pageindex }}页/共{{
                pageQuery1.totalPage
              }}页
            </el-pagination>
          </td>
          <td>
            <el-pagination
              v-model:current-page="pageQuery1.pageindex"
              v-model:page-size="pageQuery1.pagesize"
              :page-sizes="[15, 20, 30]"
              :size="size"
              background="true"
              layout="slot, prev, pager, next"
              :total="pageQuery1.totalCount"
              prev-text="上一页"
              next-text="下一页"
            >
              <el-button
                :disabled="pageQuery1.pageindex == 1"
                @click="pageQuery1.pageindex = 1"
                >首页</el-button
              >
            </el-pagination>
          </td>
          <td>
            <el-pagination
              v-model:current-page="pageQuery1.pageindex"
              v-model:page-size="pageQuery1.pagesize"
              :page-sizes="[15, 20, 30]"
              :size="size"
              background="true"
              layout="slot,jumper"
              :total="pageQuery1.totalCount"
            >
              <el-button
                :disabled="pageQuery1.pageindex == pageQuery1.totalPage"
                @click="pageQuery1.pageindex = pageQuery1.totalPage"
                >尾页</el-button
              >
            </el-pagination>
          </td>
        </tr>
      </table>
      <template #footer>
        <el-button @click="showProductDialog = false">关闭</el-button>
        <el-button type="primary" @click="onSelectProducts">选择</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed, watch } from "vue";
import { useRouter, useRoute } from "vue-router";

import { statementRed } from "@/http/axiosHelper";
import { statementWrite } from "@/http/axiosHelper";

import type { ComponentSize } from "element-plus";
import type { FormRules, FormInstance } from "element-plus";
const size = ref<ComponentSize>("default");
import axios from "axios";
import { StorageRed, StorageWrite } from "@/http/axiosHelper";
import { ElMessage, ElMessageBox } from "element-plus";

const router = useRouter();
const route = useRoute();
const form: any = reactive({
  reporting_LossesCode: "",
  losses_Type: "",
  orderCode: "",
  notes: "",
  original_location: "",
  losses_location: "",
  lossesCount: 0,
  state: "待审核",
  reviewer: null, // 审核人可以为空
  reason: null, // 审核原因可以为空
  reviewTime: null, // 审核时间可以为空
  warehouse_InOrOutId: 0,
  allotMoving_InventoryId: 0,
  product_Number: "",
  product_Name: "",
  specifications: "",
  batch: "",
  price: 0,
  createUse: "", // 用户ID（数字）
  creatorName: "", // 用户姓名（显示用）
  upDateUse: 0,
  createTime: "",
  upDataTime: "",
});

interface ProductItem {
  id: Number;
  product_Id: Number;
  product_Number: string;
  product_Name: string;
  specifications: string;
  category_ID: Number;
  category_Name: string;
  batch: string;
  storage_Unit: string;
  packaging_Type: string;
  price: string;
  weight: Number;
}

const productList: any = ref<ProductItem[]>([]);

// 控制弹窗显示
const showProductDialog = ref(false);

// 查询商品表单
const searchForm = ref({
  product_Number: "",
  product_Name: "",
});

// 商品数据（实际应从接口获取）
const productOptions = ref([]);

// 获取商品列表
function fetchProductOptions() {
  showProductDialog.value = true;
  StorageRed({
    url: "/api/Reporting_losses/GetProductByWarehouse_InOrOut",
    method: "get",
    params: {
      product_Number: searchForm.value.product_Number,
      product_Name: searchForm.value.product_Name,
      pageindex: pageQuery1.pageindex,
      pagesize: pageQuery1.pagesize,
    },
  }).then((res) => {
    productOptions.value = res.data.data;
    pageQuery1.totalCount = res.data.totalCount;
    pageQuery1.totalPage = res.data.totalPage;
  });
}

// 选中的商品
const selectedProducts = ref<ProductItem[]>([]);

// 修改 handleSelectionChange，确保深拷贝
function handleSelectionChange(val: ProductItem[]) {
  selectedProducts.value = val.map((item) => ({ ...item })); // 深拷贝
}

// 批量添加到报损产品表格
function onSelectProducts() {
  // 使用Set来快速检查重复项
  const existingProductNumbers = new Set(
    productList.value.map((item: any) => item.product_Number) // 使用product_Number作为唯一标识
  );

  // 过滤掉已经存在于表格中的产品（基于product_Number）
  const newProducts = selectedProducts.value.filter(
    (row) => !existingProductNumbers.has(row.product_Number)
  );

  // 添加新产品到表格
  productList.value.push(
    ...newProducts.map((row) => ({
      id: row.id,
      product_Id: row.product_Id,
      product_Number: row.product_Number,
      product_Name: row.product_Name,
      specifications: row.specifications,
      batch: row.batch,
      warehouse_InOrOutId: row.id,
      price: Number(row.price) || 0,
      lossesCount: 0,
      original_location: "",
      losses_location: "",
      category_ID: row.category_ID,
      category_Name: row.category_Name,
      storage_Unit: row.storage_Unit,
      packaging_Type: row.packaging_Type,
      weight: row.weight,
    }))
  );

  // 重置状态
  showProductDialog.value = false;
  selectedProducts.value = [];
}

onMounted(() => {
  loadReportingLossesData();
});

const pageQuery1: any = reactive({
  pageindex: 1,
  pagesize: 15,
  totalCount: "",
  totalPage: "",
});

// 加载报损数据
function loadReportingLossesData() {
  StorageRed({
    url: "/api/Reporting_losses/GetReporting_lossesDetail",
    method: "get",
    params: {
      reporting_LossesCode: route.query.reporting_LossesCode,
    },
  }).then((res: any) => {
    Object.assign(form, res.data.data[0]);
    // 设置产品列表
    productList.value = res.data.data.map((item: any) => ({
      id: item.id,
      product_Id: item.product_Id,
      product_Number: item.product_Number,
      product_Name: item.product_Name,
      specifications: item.specifications,
      batch: item.batch,
      warehouse_InOrOutId: item.warehouse_InOrOutId,
      price: Number(item.price) || 0,
      lossesCount: Number(item.lossesCount) || 0,
      original_location: item.original_location || "",
      losses_location: item.losses_location || "",
      category_ID: item.category_ID,
      category_Name: item.category_Name,
      storage_Unit: item.storage_Unit,
      packaging_Type: item.packaging_Type,
      weight: item.weight,
      creatorName: item.creatorName,
      createTime: item.createTime,
      createUse: item.createUse,
    }));
  });
}

// 删除产品行
function removeProduct(index: any, row: any) {
  ElMessageBox.confirm("确定要删除该产品吗？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      // 如果有报损单号，调用后端删除接口
      if (row.reporting_LossesCode) {
        StorageWrite({
          url: "/api/Reporting_losses/DeleteReporting_lossesbyWareId",
          method: "delete",
          params: {
            warehouse_InOrOutId: row.id,
          },
        }).then((res: any) => {
          if (res.data.code == 200) {
            ElMessage.success(res.data.msg);
            // 从本地列表中移除
            productList.value.splice(index, 1);
          } else {
            ElMessage.error(res.data.msg);
          }
        });
      } else {
        // 如果没有报损单号（新增的产品），直接从本地列表中移除
        productList.value.splice(index, 1);
        ElMessage.success("删除成功");
      }
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "已取消",
      });
    });
}

// 提交报损单
function onSubmit() {
  formRef.value?.validate((valid: boolean) => {
    if (!valid) {
      ElMessage.error("请完善必填项！");
      return;
    }

    // 1. 遍历产品列表，合并表单信息
    const items = productList.value.map((row: any) => ({
      ...form, // 上部分表单信息
      // 下部分产品信息，覆盖或补充form中的同名字段
      product_Id: row.product_Id,
      product_Number: row.product_Number,
      product_Name: row.product_Name,
      specifications: row.specifications,
      batch: row.batch,
      warehouse_InOrOutId: row.warehouse_InOrOutId, // 添加warehouse_InOrOutId字段
      lossesCount: Number(row.lossesCount) || 0,
      original_location: row.original_location,
      losses_location: row.original_location,
      price: Number(row.price) || 0,
      category_ID: row.category_ID,
      category_Name: row.category_Name,
      storage_Unit: row.storage_Unit,
      packaging_Type: row.packaging_Type,
      weight: row.weight,
    }));

    // 2. 组装参数对象
    const params = { items };

    // 3. 调用接口
    StorageWrite({
      url: "/api/Reporting_losses/UpdateReporting_losses",
      method: "put",
      data: params,
    }).then((res) => {
      if (res.data.code == 200) {
        ElMessage.success(res.data.msg);
        router.push("/Reporting_lossesView");
        return;
      } else {
        ElMessage.error(res.data.msg);
      }
    });
  });
}

function onCancel() {
  router.back();
}

watch(pageQuery1, () => {
  fetchProductOptions();
});

// 表单ref
const formRef = ref<FormInstance>();

// 校验规则
const rules: FormRules = {
  losses_Type: [
    { required: true, message: "报损类型不能为空", trigger: "change" },
  ],
};
</script>

<style scoped>
.add-in-storage {
  padding: 20px;
}
.form-title {
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 10px;
}
</style>
